//
//  FSVerticalTabBarController.m
//  iOS-Platform
//
//  Created by Błażej Biesiada on 4/6/12.
//  Copyright (c) 2012 Future Simple. All rights reserved.
//

#import "FSVerticalTabBarController.h"
#import "FSVerticalTableViewCell.h"
#import "BRYSerialAnimationQueue.h"

@interface FSVerticalTabBarController ()
{
    SecondLevelViewController *secondLevelVC;
   
    NSUInteger lastSelectedIndex;
    NSUInteger secondLevelID;
    NSUInteger firstLevelID;
  
    NSUInteger firstLevelLastID;
    
    
}

@property (nonatomic,strong) BRYSerialAnimationQueue *queue;
- (void)_performInitialization;
@end


@implementation FSVerticalTabBarController

@synthesize delegate = _delegate;
@synthesize tabBar = _tabBar;
@synthesize viewControllers = _viewControllers;
@synthesize selectedIndex = _selectedIndex;
@synthesize tabBarWidth = _tabBarWidth;


- (FSVerticalTabBar *)tabBar
{
    if (_tabBar == nil)
    {
        _tabBar = [[FSVerticalTabBar alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        _tabBar.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleRightMargin;
        _tabBar.delegate = self;
    }
    return _tabBar;
}


- (void)setViewControllers:(NSArray *)viewControllers
{
    _viewControllers = [viewControllers copy];
    // create tab bar items
    if (self.tabBar != nil)
    {
        NSMutableArray *tabBarItems = [NSMutableArray arrayWithCapacity:[self.viewControllers count]];
        for (UIViewController *vc in self.viewControllers)
        {
            [tabBarItems addObject:vc.tabBarItem];
        }
        self.tabBar.items = tabBarItems;
    }
    // select first VC from the new array
    // sets the value for the first time as -1 for the viewController to load itself properly
    _selectedIndex = NSNotFound;
    
    self.selectedIndex = [viewControllers count] > 0 ? 0 : INT_MAX;
    firstLevelLastID=0;
}


- (UIViewController *)selectedViewController
{
    if (self.selectedIndex < [self.viewControllers count])
    {
        return [self.viewControllers objectAtIndex:self.selectedIndex];
    }
    return nil;
}


- (void)setSelectedViewController:(UIViewController *)selectedViewController
{
    self.selectedIndex = [self.viewControllers indexOfObject:selectedViewController];
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    if (secondLevelVC.view!=nil) {
         [secondLevelVC.view removeFromSuperview];
        [secondLevelVC removeFromParentViewController];
       
    }
//    if (selectedIndex != _selectedIndex && selectedIndex < [self.viewControllers count])
//    {
    if ( selectedIndex < [self.viewControllers count])
            {
        if (_selectedIndex != NSNotFound)
        {
            UIViewController *previousViewController = [self.viewControllers objectAtIndex:_selectedIndex];
            [previousViewController.view removeFromSuperview];
            [previousViewController removeFromParentViewController];
        }
        
        // add new view controller to hierarchy
        UIViewController *selectedViewController = [self.viewControllers objectAtIndex:selectedIndex];
        [self addChildViewController:selectedViewController];
        selectedViewController.view.frame = CGRectMake(self.tabBarWidth,
                                                       0,
                                                       self.view.bounds.size.width-self.tabBarWidth+1,
                                                       self.view.bounds.size.height);
        selectedViewController.view.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        [self.view addSubview:selectedViewController.view];
        // remove previously selected view controller (if any)
    lastSelectedIndex=_selectedIndex;
      firstLevelLastID=selectedIndex;
      _selectedIndex = selectedIndex;

     if (selectedIndex < [self.tabBar.items count])
        {
          self.tabBar.selectedItem = [self.tabBar.items objectAtIndex:selectedIndex];
            [self.tabBar reloadData];
        }
        // inform delegate
        if ([self.delegate respondsToSelector:@selector(tabBarController:didSelectViewController:)])
        {
            [self.delegate tabBarController:self didSelectViewController:selectedViewController];
        }
        
    }
   
}

- (void)_performInitialization
{
    self.tabBarWidth = DEFAULT_TAB_BAR_HEIGHT;
    self.selectedIndex = NSNotFound;
    lastSelectedIndex=0;
}

#pragma mark -
#pragma mark UIViewController
- (id)init
{
    if ((self = [super init]))
    {
        [self _performInitialization];
         _queue = [[BRYSerialAnimationQueue alloc] init];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super initWithCoder:aDecoder]))
    {
        [self _performInitialization];
    }
    return self;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self _performInitialization];
    }
    return self;
}


- (void)loadView
{
    UIView *layoutContainerView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    layoutContainerView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    layoutContainerView.autoresizesSubviews = YES;
    
    self.tableviewContainer=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tabBarWidth, layoutContainerView.bounds.size.height)];
  
   self.bgImageView=[[UIImageView alloc] initWithFrame: CGRectMake(0, 0, self.tabBarWidth,130)];
    [self.bgImageView setBackgroundColor:[UIColor colorWithRed:17.0f/255.0f green:19.0f/255.0f blue:24.0f/255.0f alpha:1.0]];
    [self.tableviewContainer addSubview:self.bgImageView];
    
//    self.lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.tabBarWidth,50,1.0f, layoutContainerView.bounds.size.height-50)];
//    self.lineLabel.backgroundColor = [UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1.0];
//    [self.tableviewContainer addSubview:self.lineLabel];
    
    // create tab bar
    self.tabBar.frame = CGRectMake(0,self.bgImageView.frame.size.height, self.tabBarWidth, layoutContainerView.bounds.size.height);
    self.tabBar.backgroundColor=[UIColor colorWithRed:17.0f/255.0f green:19.0f/255.0f blue:24.0f/255.0f alpha:1.0];
     //self.tabBar.backgroundColor=[UIColor clearColor];
    [self.tableviewContainer addSubview:self.tabBar];
    [self.tableviewContainer setBackgroundColor:[UIColor whiteColor]];
    [layoutContainerView addSubview:self.tableviewContainer];
    
    self.view = layoutContainerView;
    [self.tableviewContainer bringSubviewToFront:self.tabBar];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    UIViewController *selectedViewController = self.selectedViewController;
    if (selectedViewController != nil)
    {
        return [selectedViewController shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
    }
    return YES;
}
#pragma mark -
#pragma mark FSVerticalTabBarController
- (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated
{
    self.viewControllers = viewControllers;
}
#pragma mark -
#pragma mark <UITableViewDelegate>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // NSLog(@"cellID===%d",_cellID);
    //[HttpRequest cancelRequest];
    if(indexPath.row==0)
    {
     
         [self setSelectedIndex:indexPath.row];
    }
   else if (indexPath.row==1) {
      
        [Global setProductID:0];
         [self setSelectedIndex:indexPath.row];
    }
   //  NSLog(@"2222222====%d",indexPath.row);
   else if(indexPath.row==4||indexPath.row==6||indexPath.row==8) //(indexPath.row==1||indexPath.row==2||indexPath.row==8)
    {
        
        if (indexPath.row!=_cellID) {
           
        
          [self setSelectedIndex:indexPath.row];
        }
       
        
    }
    
    else
    {
       
       // if (cellID!=indexPath.row) {
        firstLevelID=indexPath.row;
        [self addSecondLevelView:indexPath.row];
       
       // }
    }
    _cellID=indexPath.row;
    
   // secondLevelPreviousID=NSNotFound;
    [self.view bringSubviewToFront:self.tableviewContainer];
   
}
-(void)setLastSelectedItem
{
    if (lastSelectedIndex < [self.viewControllers count])
    {
        
        self.tabBar.selectedItem = [self.tabBar.items objectAtIndex:lastSelectedIndex];
        
        [self.tabBar reloadData];
        
    }
}

-(void)addSecondLevelView:(NSUInteger)selectID
{
//    if (selectID != _selectedIndex && selectID < [self.viewControllers count])
//    {
    if (secondLevelVC.view!=nil) {
        [secondLevelVC removeFromParentViewController];
        [secondLevelVC.view removeFromSuperview];
    }
    //_selectedIndex =firstLevelID;
    self.tabBar.selectedItem = [self.tabBar.items objectAtIndex:selectID];
    [self.tabBar reloadData];
    secondLevelVC=[[SecondLevelViewController alloc] init];
    secondLevelVC.delegate=self;
    if (selectID==2) {
        secondLevelVC.cellCount=6;
        secondLevelVC.tableID=@"SHOPGUIDE";
    }
//    else if (selectID==2)
//    {
//        secondLevelVC.cellCount=10;
//        secondLevelVC.tableID=@"PRODUCT";
//    }
    else if (selectID==3)
    {
        secondLevelVC.cellCount=6;
        secondLevelVC.tableID=@"STOCK";
    }
//    else if (selectID==4)
//    {
//        secondLevelVC.cellCount=1;
//        secondLevelVC.tableID=@"ANALYSIS";
//    }

//    else if (selectID==5)
//    {
//        secondLevelVC.cellCount=3;
//        secondLevelVC.tableID=@"FACTORY";
//    }
    else if (selectID==8)
    {
        secondLevelVC.cellCount=3;
        secondLevelVC.tableID=@"SHOPAFFAIR";
    }
    secondLevelVC.view.frame = CGRectMake(self.tabBarWidth,
                                                       0,
                                                       self.view.bounds.size.width-self.tabBarWidth,
                                                       self.view.bounds.size.height);
    secondLevelVC.view.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        [self addChildViewController:secondLevelVC];
        [self.view addSubview:secondLevelVC.view];
        
        
        void (^updateLabelOriginX)(CGFloat) = ^(CGFloat originX) {
            CGRect frame = secondLevelVC.blurView.frame;
            frame.origin.x = originX;
            secondLevelVC.blurView.frame = frame;
            
            CGRect tableframe = secondLevelVC.secondLevelTableView.frame;
            tableframe.origin.x = originX;
            secondLevelVC.secondLevelTableView.frame = tableframe;
        };
        
        [self.queue animateWithDuration:0.4 delay:0 options:0 animations:^{
            
            updateLabelOriginX(0);
            
        } completion:^(BOOL finished) {
            
        }];
   // }

}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL result;
   
    if ([self.delegate respondsToSelector:@selector(tabBarController:shouldSelectViewController:)]) {
        UIViewController *newController = [self.viewControllers objectAtIndex:indexPath.row];
        result = [self.delegate tabBarController:self shouldSelectViewController:newController];
    }
    if (result) {
        return indexPath;
    }
    else {
        return tableView.indexPathForSelectedRow;
    }
}

#pragma mark SecondLevelDelegate Method
-(void)alphaViewClick
{
    if (secondLevelVC.view!=nil) {
        [secondLevelVC removeFromParentViewController];
        [secondLevelVC.view removeFromSuperview];
    }
    lastSelectedIndex=firstLevelLastID;
    _cellID=firstLevelLastID;
    [self setLastSelectedItem];
    for (int i=0; i<9; i++) {
        NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell *cell = [self.tabBar cellForRowAtIndexPath:indexPath1];
        FSVerticalTableViewCell *fsCell=( FSVerticalTableViewCell *)cell;
       // fsCell.sliderImageView.hidden=YES;
        fsCell.sanjiaoImageView.hidden=YES;
    }
}
-(void)tableCellClick:(NSUInteger)index
{
   // [HttpRequest cancelRequest];
    [Global hideProgressHUDInternal:self.view];
    if (firstLevelID==2) {
       
        [Global setShopGuideID:index];
    }
//    if (firstLevelID==2) {
//        [Global setProductID:index];
//       // NSLog(@"index/////=%d",index);
//       // [Global setShopAffairID:index];
//    }
    if (firstLevelID==3) {
        [Global setStockID:index];
    }
    if (firstLevelID==8) {
        [Global setMyAccountID:index];
    }

    if (secondLevelVC.view!=nil) {
        [secondLevelVC removeFromParentViewController];
        [secondLevelVC.view removeFromSuperview];
    }
    [self setSelectedIndex:firstLevelID];
    lastSelectedIndex=_selectedIndex;
    firstLevelLastID=_selectedIndex;
    _selectedIndex =firstLevelID;
    
    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:_selectedIndex inSection:0];
    UITableViewCell *cell = [self.tabBar cellForRowAtIndexPath:indexPath1];
    FSVerticalTableViewCell *fsCell=( FSVerticalTableViewCell *)cell;
   // fsCell.sliderImageView.hidden=YES;
    fsCell.sanjiaoImageView.hidden=YES;
    
    
    if ([self.delegate respondsToSelector:@selector(secondLevelCellClick)])
    {
        [self.delegate secondLevelCellClick];
    }

    
 }
@end
